<template>
  <div class="app_user h100" v-loading="loading">
    <div class="pageContent">
      <el-row :gutter="11" class="fileSearch">
        <el-form :model="ruleForm" :inline="true" ref="ruleForm" label-width="80px">
          <el-form-item label="用户昵称:" prop="username">
            <el-input v-model="ruleForm.username" clearable></el-input>
          </el-form-item>
          <el-form-item label="手机号:" prop="phone">
            <el-input v-model="ruleForm.phone" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="onSubmit(1)">
              查询
            </el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
            <el-button icon="el-icon-plus" type="success" @click="dialogVisible = true"
              >新增</el-button
            >
          </el-form-item>
        </el-form>
      </el-row>
      <dic class="table_wrapper">
        <el-table
        :data="tableData"
        border
        :header-cell-style="{
          background: 'rgb(246,247,251)',
          color: '#606266',
        }"
        stripe
        class="defaultTableHeight"
      >
        <el-table-column type="index" label="编号" width="50"> </el-table-column>
        <el-table-column prop="username" align="center" label="用户昵称">
        </el-table-column>
        <el-table-column prop="phone" align="center" label="手机号"> </el-table-column>
        <el-table-column prop="realname" align="center" label="真实姓名">
        </el-table-column>
        <el-table-column prop="avatarUrl" align="center" label="头像">
          <template slot-scope="scope">
            <el-image class="avatarUrl_img" :src="scope.row.avatarUrl" alt=""></el-image>
          </template>
        </el-table-column>

        <el-table-column prop="status" align="center" label="操作" width="280">
          <template slot-scope="scope">
            <el-button type="success" size="mini" @click="isDisable(scope.row)">
              编辑
            </el-button>

            <el-button
              v-if="
                !(
                  scope.row.username == 'admin' ||
                  (scope.row.username == userInfo.userName &&
                    scope.row.id == userInfo.userId)
                )
              "
              :type="scope.row.status == 1 ? 'danger' : 'primary'"
              size="mini"
              @click="changeState(scope.row)"
            >
              {{ scope.row.status == 1 ? "禁用" : "启用" }}
            </el-button>
            <el-button
              v-if="
                !(
                  scope.row.username == 'admin' ||
                  (scope.row.username == userInfo.userName &&
                    scope.row.id == userInfo.userId)
                )
              "
              type="danger"
              size="mini"
              @click="del(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <p style="text-align: right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pager.currentPage"
          :page-size="pager.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          background
          layout="total,sizes,prev, pager, next, jumper"
          :total="pager.total"
        >
        </el-pagination>
      </p>
      </dic>
    </div>
    <el-dialog
      :title="titleName"
      :visible.sync="dialogVisible"
      width="600px"
      v-dialogDrag
      @close="closeDialog"
    >
      <el-form
        ref="goodsForm"
        :model="goodsForm"
        :rules="goodsFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="goodsForm.username" :disabled="usernameShow"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="goodsForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" prop="realname">
          <el-input v-model="goodsForm.realname"></el-input>
        </el-form-item>
        <el-form-item label="头像" style="height: 120px" prop="avatarUrl">
          <div v-if="!goodsForm.avatarUrl" class="file_img img_text" @click="imgClick()">
            上传图片
          </div>
          <img class="file_img" :src="goodsForm.avatarUrl" @click="imgClick()" />
          <input
            class="file_input"
            type="file"
            id="file"
            accept=".png,.jpg,.jpeg"
            @change="change"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="closeDialog">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  adminList,
  adminOperation,
  adminChangeUser,
  admindeleteUser,
  adminDisables,
} from "@/api/adminUser/index";
export default {
  name: "adminUser",
  data() {
    const isUserName = async (rule, value, callback) => {
      let postData = {
        id: this.goodsForm.id,
        username: value,
      };
      console.log(postData, "postData");
      try {
        const res = await adminChangeUser(postData);
        console.log(res, 200);
        if (res.code === "2000") {
          callback();
          return;
        }
        callback(new Error(res.msg || "数据验证失败"));
      } catch (err) {
        console.log(err, 404);
        callback(new Error(res.msg || "数据验证失败"));
      }
    };
    // // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback();
      } else {
        var isMob = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
        var isPhone = /^1[345678]\d{9}$/;
        if (isMob.test(value) || isPhone.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的手机号"));
        }
      }
    };
    return {
      titleName: "新增用户信息",
      loading: false,
      dialogVisible: false, // 编辑弹窗
      usernameShow: false,

      userInfo: "",
      ruleForm: {
        username: "",
        phone: "",
      },
      pager: {
        pageSize: 20,
        total: 1,
        currentPage: 1,
      },
      tableData: [],
      goodsForm: {
        id: "",
        username: "",
        phone: "",
        realname: "",
        avatarUrl: "",
      },
      goodsFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { validator: isUserName, trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
      },
      detailsList: [],
    };
  },
  mounted() {
    this.userInfo = JSON.parse(localStorage.getItem("UserInfo"));
    this.onSubmit();
  },
  //注销window.onresize事件
  destroyed() {},
  methods: {
    async onSubmit(val) {
      if (val) {
        this.pager.currentPage = 1;
      }
      this.loading = true;
      let postData = {
        username: this.ruleForm.username,
        phone: this.ruleForm.phone,
        pageSize: this.pager.pageSize,
        currentPage: this.pager.currentPage,
      };
      console.log(postData, "postData");
      try {
        const res = await adminList(postData);
        this.loading = false;
        console.log(res, 200);
        if (res.code !== "2000") {
          this.$message(res.msg ? res.msg : "数据读取失败");
          return;
        }
        this.tableData = res.data;
        this.pager.pageSize = res.pageSize;
        this.pager.total = res.total;
        this.pager.currentPage = res.currentPage;

        //数据读取成功
      } catch (err) {
        this.loading = false;
        console.log(err, 404);
        this.$message.error(err.msg);
        this.tableData = [];
      }
    },
    // 启用禁用
    async setChangeState(paramet) {
      this.loading = true;
      let status = paramet.status == 0 ? 1 : 0;
      let postData = {
        id: paramet.id,
        status: status,
      };
      console.log(postData, "postData");
      try {
        const res = await adminDisables(postData);
        console.log(res, 200);
        this.loading = false;
        if (res.code !== "2000") {
          this.$message.error(res.msg ? res.msg : "操作失败");
          return;
        }
        this.$message.success("操作成功");
        this.onSubmit();
      } catch (err) {
        this.loading = false;
        console.log(err, 404);
        this.$message.error(err.msg);
      }
    },
    changeState(paramet) {
      if (paramet.status == 0) {
        this.setChangeState(paramet);
      } else {
        this.$confirm("此操作将禁用该用户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.setChangeState(paramet);
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消操作",
            });
          });
      }
    },

    // 触发图片选择
    imgClick() {
      document.querySelector("#file").click();
    },
    // 选择图片
    change() {
      console.log(1);
      let file = document.querySelector("#file").files[0];
      var reader = new FileReader();
      var that = this;
      console.log("base64", file);
      reader.onloadend = function () {
        //把转换后的数据给id为base64Img的src属性
        console.log(reader.result);
        that.goodsForm.avatarUrl = reader.result;
        //这里调用了向后台发请求的代码
      };
      if (file) {
        reader.readAsDataURL(file);
      }
    },

    // 打开编辑弹窗
    isDisable(data) {
      this.titleName = "编辑用户信息";
      this.dialogVisible = true;
      let { avatarUrl, id, phone, realname, username } = JSON.parse(JSON.stringify(data));
      if (username == "admin") {
        this.usernameShow = true;
        // this.$refs["username"].style.display = none;
      } else {
        this.usernameShow = false;
      }
      this.goodsForm = { avatarUrl, id, phone, realname, username };
    },

    //保存修改
    submitForm() {
      let that = this;
      this.$refs["goodsForm"].validate(async (valid) => {
        console.log(valid, "valid");
        if (valid) {
          let postData;
          if (that.goodsForm.avatarUrl.indexOf("http") == -1) {
            postData = JSON.parse(
              JSON.stringify(that.goodsForm).replace(/avatarUrl/g, "base64File")
            );
          } else {
            let { avatarUrl, id, phone, realname, username } = that.goodsForm;
            postData = { base64File: "", id, phone, realname, username };
          }
          console.log(postData, "postData");
          try {
            const res = await adminOperation(postData);
            console.log(res, 200);
            if (res.code === "2000") {
              this.$message.success(res.msg);
              this.dialogVisible = false;
              this.onSubmit();
              return;
            }
            this.$message.fail(res.msg || "修改失败");
          } catch (err) {
            console.log(err, 404);
            this.$message.fail(err.msg);
          }
        }
      });
    },

    del(id) {
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let postData = {
            id,
          };
          console.log(postData, "postData");
          try {
            const res = await admindeleteUser(postData);
            console.log(res, 200);
            if (res.code === "2000") {
              this.$message.success("删除成功");
              this.onSubmit();
              return;
            }
            this.$message.fail(res.msg || "删除失败");
          } catch (err) {
            console.log(err, 404);
            this.$message.fail(err.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 关闭弹窗的回调
    closeDialog() {
      this.goodsForm = {
        id: "",
        username: "",
        phone: "",
        realname: "",
        avatarUrl: "",
      };
      this.$refs["goodsForm"].resetFields();
      this.dialogVisible = false;
      this.usernameShow = false;
      this.titleName = "新增用户信息";
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$refs["ruleForm"].resetFields();
      this.onSubmit();
    },
    // 初始页currentPage、初始每页数据数pagesize和数据data
    handleSizeChange: function (size) {
      this.pager.pageSize = size;
      this.onSubmit();
    },
    handleCurrentChange: function (currentPage) {
      this.pager.currentPage = currentPage;
      this.onSubmit(); //点击第几页
    },
  },
};
</script>

<style lang="scss" scoped>
.img_text {
  text-align: center;
  background-color: #fff;
  line-height: 100px;
  z-index: 1;
  border: 1px solid #f0f0f0;
}
.file_img {
  position: absolute;
  top: 9px;
  width: 100px;
  height: 100px;
  cursor: pointer;
  border: 1px solid #eeeeee;
}
.file_input {
  color: #ffffff00;
  display: none;
  width: 100px;
  height: 100px;
}
.avatarUrl_img {
  width: 70px;
  height: 70px;
  border: 1px solid #eeeeee;
}
.el-button {
  margin: 2px;
}
.el-dialog {
  width: 100px;
}
</style>
